import datetime
import time


def str2date(date_str, date_format="%Y-%m-%d"):
    '''
    字符串转date
    '''
    if date_str:
        return datetime.datetime.strptime(date_str, date_format)
    return None


def date2str(date, date_format="%Y-%m-%d"):
    '''
    日期转字符串
    '''
    if date:
        return date.strftime(date_format)
    return None


def date_delta(date_str, gap, format="%Y-%m-%d"):
    '''
    几天前的日期字符串
    '''
    date = str2date(date_str)
    pre_date = date + datetime.timedelta(days=-gap)
    return date2str(pre_date, format)  # date形式转化为str


def str2timestamp(str, timestamp_len=10):
    '''
    字符串转时间戳
    '''
    date_array = time.strptime(str, "%Y-%m-%d %H:%M:%S")
    timestamp = int(time.mktime(date_array))
    if timestamp_len == 13:
        timestamp *= 1000
    return timestamp
